import { exec } from 'child_process';

let prefix: string = '';
let dataPath: string = '';

export const setPrefix = (str: string) => {
  prefix = str;
  console.log('set prefix: ', str);
};

export const getPrefix = () => {
  return prefix;
};

export const setDataPath = (path: string) => {
  dataPath = path;
  console.log('set dataPath: ', path);
};

export const getDataPath = () => {
  return dataPath;
};

export const cmdExec = (cmd: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    const prefix = getPrefix();
    exec(`${prefix}${cmd}`, (error, stdout) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(stdout);
    });
  });
};

export const getCurrentVersion = async (SN: string, name: string) => {
  let version = '';
  const cmd = `hdc ${
    SN ? `-t ${SN}` : ''
  } shell "bm dump -n ${name} | grep versionName"`;
  try {
    const versions: string[] = await cmdExec(cmd).then(
      (res) => res.toString().split(/[(\r\n)\r\n]/) || [],
    );
    for (let i = versions.length - 1; i >= 0; i--) {
      if (version) break;
      if (versions[i].indexOf('versionName') < 0) continue;
      const params = versions[i].split('"');
      for (let j = params.length - 1; j >= 0; j--) {
        if (!isNaN(+params[j].split('')[0])) {
          version = params[j];
          break;
        }
      }
    }
  } catch (err) {
    console.log(err);
  }
  return version;
};

export const delay = (time: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
};
